package cn.hr.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hr.pojo.Archives;
import cn.hr.pojo.SysUser;
import cn.hr.pojo.Train;
import cn.hr.service.DictionaryService;
import cn.hr.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.hr.service.TrainService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 培训控制器
 *
 * @author MO
 */
@Controller
@RequestMapping("/sys/train")
public class TrainController {
    private Logger logger = LoggerFactory.getLogger(TrainController.class);
    @Resource
    private TrainService trainService;

    @Resource
    private DictionaryService dictionaryService;

    @RequestMapping("/trainList")
    public String list(@RequestParam(required = false) Map map, @RequestParam(defaultValue = "1") Integer pageNo, Model model) {
        PageInfo<Map> pageInfo = null;
        try {
            pageInfo = trainService.findListByCondition(map, pageNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("pageInfo", pageInfo);
        return "train/trainShow";
    }

    @RequestMapping("/trainShow")
    //主页数据显示跳转
    public String trainShow() {
        return "train/trainList";
    }


    @RequestMapping("/trainStatus")
    @ResponseBody
    //查询审核状态
    public Object trainStatus() {
        try {
            return dictionaryService.selectAllByTypeName("AUDITSTATUS_TYPE");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/add")
    public String add() {
        return "train/trainAdd";
    }

    @RequestMapping("/addSave")
    public String addSave(Train train, HttpSession session, @RequestParam(value = "attach", required = false) MultipartFile attach,@RequestParam Integer num) {
        String trainData = null;
        boolean flag = true;
        String oldFileName = null;
        //String path = "D:/GitBoot/HRSystem_SpringBoot/src/main/resources" + File.separator + "static" + File.separator + "upload";
        try {
            if (!attach.isEmpty()) {
                oldFileName = attach.getOriginalFilename();//获取原文件名
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                int fileSize = 900000000;
                if (attach.getSize() > fileSize) {
                    flag = false;
                } else if (prefix.equalsIgnoreCase("zip") || prefix.equalsIgnoreCase("rar")) {
                    File targetFile = new File(Constants.BASEPATH,oldFileName);
                    if (!targetFile.exists()) {
                        targetFile.getParentFile().mkdir();
                        targetFile.createNewFile();
                    }
                    attach.transferTo(targetFile);
                    trainData = Constants.BASEPATH + File.separator + oldFileName;
                } else {
                    flag = false;
                }
            }
            if (flag) {
                train.setFileName(oldFileName);
                train.setTrainData(trainData);
                train.setAuditStatus(num);
                train.setCreatedById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
                train.setCreatedDate(new Date());
                if (trainService.insert(train)) {
                    return "redirect:/sys/train/trainShow";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/sys/train/trainAdd";
    }

    @RequestMapping("/update")
    //修改跳转页面
    public String getTrain(@RequestParam Integer id, @RequestParam Integer i, Model model) {
        Train train = null;
        try {
            train = trainService.get(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("train", train);
        model.addAttribute("i", i);
        if (i==2){
            return "train/trainFeedback";
        }
        return "train/trainModify";
    }

    @RequestMapping("/updateSave")
    public String updateSave(Train train, @RequestParam(value = "attach", required = false) MultipartFile attach, HttpSession session) {
        boolean flag = true;
        String oldFileName = attach.getOriginalFilename();//获取文件名
        String prefix = FilenameUtils.getExtension(oldFileName);//获取文件后缀
        //String path = "D:/GitBoot/HRSystem_SpringBoot/src/main/resources" + File.separator + "static" + File.separator + "upload";
        int fileSize = 900000000;
        try {
            if (!attach.isEmpty()) {
                if (attach.getSize() > fileSize) {
                    flag = false;
                } else if (prefix.equalsIgnoreCase("zip") || prefix.equalsIgnoreCase("rar")) {
                    File targetFile = new File(Constants.BASEPATH, oldFileName);
                    if (!targetFile.exists()) {
                        targetFile.getParentFile().mkdir();
                        targetFile.createNewFile();
                    }
                    attach.transferTo(targetFile);
                } else {
                    flag = false;
                }
            }
            if (flag) {
                train.setFileName(oldFileName);
                train.setTrainData(Constants.BASEPATH+File.separator+oldFileName);
                train.setModifyById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
                train.setModifyDate(new Date());
                if (trainService.update(train)) {
                    return "redirect:/sys/train/trainShow";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/sys/train/update";
    }

    @RequestMapping("/delFile")
    @ResponseBody
    //删除文件
    public Object delFile(@RequestParam Integer id) {
        Map<String, Object> result = new HashMap<>();
        if (id == null || id == 0) {
            result.put("result", "false");
        }
        try {
            if (trainService.delFile(id)) {
                result.put("result", "true");
            } else {
                result.put("result", "false");
            }
        } catch (SQLException e) {
            result.put("result", "false");
            e.printStackTrace();
        }
        return JSON.toJSONString(result);
    }

    @RequestMapping("/feedbackRank")
    @ResponseBody
    //变更类型
    public Object feedbackRank() {
        try {
            return dictionaryService.selectAllByTypeName("FEEDBACK_TYPE");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("feedback")
    public String feedback(Train train){
        try {
            if (trainService.feedback(train)){
                return "redirect:/sys/train/trainShow";
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "redirect:sys/train/trainShow";
    }

    @RequestMapping("/delete")
    @ResponseBody
    //删除数据
    public Object delete(@RequestParam Integer id) {
        try {
            return trainService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //文件下载相关代码
    @RequestMapping("/downloadFile")
    public String downloadFile(@RequestParam("id") Integer id, HttpServletResponse response) {
        Train train = null;
        String fileName = null;
        try {
            train = trainService.selectPath(id);
            fileName = train.getFileName();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (fileName != null) {
            File file = new File(train.getTrainData());
            if (file.exists()) {
                response.setContentType("application/force-download");
                try {
                    response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));//设置下载文件名
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }


}
